package com.example.tomatotodo.adapter;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.tomatotodo.FocusActivity;
import com.example.tomatotodo.R;
import com.example.tomatotodo.model.TodoConstants;
import com.example.tomatotodo.model.TodoItem;
import com.example.tomatotodo.model.TodoRecordSyncDTO;
import com.example.tomatotodo.model.TodoSettingDTO;
import com.example.tomatotodo.util.RecordUtil;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

public class TodoAdapter extends RecyclerView.Adapter<TodoAdapter.TodoViewHolder> {

    private static final String TAG = "TodoAdapter";
    private final List<TodoItem> todoList;
    private OnItemLongClickListener longClickListener;
    private OnItemClickListener clickListener; // 添加点击监听器

    public interface OnItemLongClickListener {
        void onItemLongClick(int position);
    }

    // 添加点击监听器接口
    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemLongClickListener(OnItemLongClickListener listener) {
        this.longClickListener = listener;
    }

    // 添加设置点击监听器的方法
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.clickListener = listener;
    }

    public TodoAdapter(List<TodoItem> todoList) {
        this.todoList = todoList;
    }

    @NonNull
    @Override
    public TodoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_todo_card, parent, false);
        return new TodoViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull TodoViewHolder holder, int position) {
        TodoItem item = todoList.get(position);
        holder.tvName.setText(item.getName());

        // 根据类型显示相应的中文描述
        String type = item.getType();
        if (TodoConstants.TYPE_POMODORO.equals(type)) {
            holder.tvCategory.setText("普通番茄钟");
        } else if (TodoConstants.TYPE_GOAL.equals(type)) {
            holder.tvCategory.setText("定目标");
        } else {
            holder.tvCategory.setText(type); // 如果不是预定义类型，则直接显示原值
        }

        // 设置卡片背景颜色
        holder.cardBackground.setBackgroundTintList(ColorStateList.valueOf(item.getColor()));

        // 获取任务记录
        AtomicReference<Context> context = new AtomicReference<>(holder.itemView.getContext());
        List<TodoRecordSyncDTO> records = RecordUtil.getRecordsByTaskId(context.get(), item.getId());
        List<TodoRecordSyncDTO> completedRecords = records.stream()
                .filter(record -> Boolean.TRUE.equals(record.getFinished()))
                .collect(Collectors.toList());

        // 获取今天的完成次数
        LocalDate today = LocalDate.now();
        long todayCompletedCount = completedRecords.stream()
                .filter(record -> record.getClientCreatedAt() != null &&
                        record.getClientCreatedAt().toLocalDate().equals(today))
                .count();

        // 处理不同类型的任务显示
        if (TodoConstants.TYPE_POMODORO.equals(type)) {
            // 普通番茄钟模式
            handlePomodoroMode(holder, item, (int) todayCompletedCount);
        } else if (TodoConstants.TYPE_GOAL.equals(type)) {
            // 定目标模式
            handleGoalMode(holder, item, completedRecords, (int) todayCompletedCount);
        }

        // 设置触摸监听器实现按下缩小效果
        holder.itemView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 添加缩放和透明度动画
                        ObjectAnimator scaleX = ObjectAnimator.ofFloat(v, "scaleX", 1f, 0.9f);
                        ObjectAnimator scaleY = ObjectAnimator.ofFloat(v, "scaleY", 1f, 0.9f);
                        ObjectAnimator alpha = ObjectAnimator.ofFloat(v, "alpha", 1f, 0.8f);

                        scaleX.setDuration(200);
                        scaleY.setDuration(200);
                        alpha.setDuration(200);

                        scaleX.setInterpolator(new AccelerateDecelerateInterpolator());
                        scaleY.setInterpolator(new AccelerateDecelerateInterpolator());
                        alpha.setInterpolator(new AccelerateDecelerateInterpolator());

                        AnimatorSet animatorSet = new AnimatorSet();
                        animatorSet.playTogether(scaleX, scaleY, alpha);
                        animatorSet.start();
                        break;

                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        // 恢复原始大小
                        restoreView(v);
                        break;
                }
                return false; // 返回false以便长按事件能够正常工作
            }
        });

        // 设置长按监听器
        holder.itemView.setOnLongClickListener(v -> {
            int adapterPosition = holder.getAdapterPosition();
            Log.d(TAG, "检测到长按事件，位置: " + adapterPosition);

            // 恢复原始大小
            restoreView(v);

            if (longClickListener != null && adapterPosition != RecyclerView.NO_POSITION) {
                longClickListener.onItemLongClick(adapterPosition);
                return true;
            }
            return false;
        });

        // 设置点击监听器
        holder.itemView.setOnClickListener(v -> {
            int adapterPosition = holder.getAdapterPosition();
            Log.d(TAG, "检测到点击事件，位置: " + adapterPosition);

            // 恢复原始大小
            restoreView(v);

            if (clickListener != null && adapterPosition != RecyclerView.NO_POSITION) {
                clickListener.onItemClick(adapterPosition);
            }
        });

        // 设置开始按钮点击监听器
        holder.btnStart.setOnClickListener(v -> {
            int adapterPosition = holder.getAdapterPosition();
            Log.d(TAG, "检测到开始按钮点击事件，位置: " + adapterPosition);

            if (adapterPosition != RecyclerView.NO_POSITION) {
                TodoItem todoItem = todoList.get(adapterPosition);
                context.set(holder.itemView.getContext());

                // 检查是否为不计时模式
                if (TodoConstants.TIMER_MODE_NO_TIMER.equals(todoItem.getSetting().getTimerMode())) {
                    // 弹出确认对话框
                    new AlertDialog.Builder(context.get())
                            .setTitle("打卡提示")
                            .setMessage("[不计时]类型的待办，点击确认即可完成一次。\n确定要完成一次吗？")
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 创建不计时记录
                                TodoRecordSyncDTO record = new TodoRecordSyncDTO();
                                LocalDateTime now = LocalDateTime.now();
                                record.setClientCreatedAt(now);
                                record.setStartTime(now);
                                // 结束时间设置为开始时间减去1秒，作为不计时记录的特征
                                record.setEndTime(now.minusSeconds(1));
                                record.setFinished(true);

                                // 设置任务关联信息
                                record.setTaskId(todoItem.getId());
                                record.setTaskTitle(todoItem.getSetting().getTitle());
                                record.setTaskType(todoItem.getSetting().getType());

                                // 保存记录到SharedPreferences
                                saveRecordToPreferences(context.get(), record);

                                // 显示完成提示
                                Toast.makeText(context.get(), "任务已完成", Toast.LENGTH_SHORT).show();
                            })
                            .setNegativeButton("取消", null)
                            .show();
                } else {
                    // 启动专注界面Activity
                    Intent intent = new Intent(context.get(), FocusActivity.class);
                    intent.putExtra("todo_item", todoItem);
                    context.get().startActivity(intent);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return todoList.size();
    }

    // 添加删除项目的方法
    public void removeItem(int position) {
        if (position >= 0 && position < todoList.size()) {
            todoList.remove(position);
            notifyItemRemoved(position);
        }
    }

    static class TodoViewHolder extends RecyclerView.ViewHolder {
        TextView tvName, tvCategory, btnStart;
        LinearLayout cardBackground;
        TextView tvTaskProgress; // 新增：任务进度
        TextView tvStartInfo;    // 新增：开始按钮上方信息
        TextView tvCompletionInfo; // 新增：完成信息

        public TodoViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tv_task_name);
            tvCategory = itemView.findViewById(R.id.tv_task_category);
            btnStart = itemView.findViewById(R.id.btn_start);
            cardBackground = itemView.findViewById(R.id.card_background);
            tvTaskProgress = itemView.findViewById(R.id.tv_task_progress); // 新增
            tvStartInfo = itemView.findViewById(R.id.tv_start_info);       // 新增
            tvCompletionInfo = itemView.findViewById(R.id.tv_completion_info); // 新增
        }
    }

    // 恢复视图到原始状态的方法
    private void restoreView(View view) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 1f);

        scaleX.setDuration(200);
        scaleY.setDuration(200);
        alpha.setDuration(200);

        scaleX.setInterpolator(new AccelerateDecelerateInterpolator());
        scaleY.setInterpolator(new AccelerateDecelerateInterpolator());
        alpha.setInterpolator(new AccelerateDecelerateInterpolator());

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleX, scaleY, alpha);
        animatorSet.start();
    }

    /**
     * 处理普通番茄钟模式的显示逻辑
     */
    private void handlePomodoroMode(TodoViewHolder holder, TodoItem item, int todayCompletedCount) {
        Log.d(TAG, "handlePomodoroMode: 处理普通番茄钟模式显示逻辑，任务ID: " + item.getId() + "，今日完成次数: " + todayCompletedCount);
        // 如果今日已完成次数大于0，显示删除线和完成信息
        if (todayCompletedCount > 0) {
            holder.tvName.setPaintFlags(holder.tvName.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            holder.tvCompletionInfo.setVisibility(View.VISIBLE);
            holder.tvCompletionInfo.setText("今日已完成" + todayCompletedCount + "次");
        } else {
            // 否则取消删除线
            holder.tvName.setPaintFlags(holder.tvName.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
            holder.tvCompletionInfo.setVisibility(View.INVISIBLE);
        }

        // 隐藏定目标模式特有的UI元素
        holder.tvTaskProgress.setVisibility(View.INVISIBLE);
        holder.tvStartInfo.setVisibility(View.INVISIBLE);
    }

    /**
     * 处理定目标模式的显示逻辑
     */
    private void handleGoalMode(TodoViewHolder holder, TodoItem item, List<TodoRecordSyncDTO> completedRecords,
                                int todayCompletedCount) {
        Log.d(TAG, "handleGoalMode: 处理定目标模式显示逻辑，任务ID: " + item.getId() + "，已完成记录数: " + completedRecords.size() + "，今日完成次数: " + todayCompletedCount);
        TodoSettingDTO setting = item.getSetting();

        // 计算目标进度
        int progress = calculateGoalProgress(setting, completedRecords);

        // 显示进度
        String unit = "分钟";
        int displayGoalValue = setting.getGoalTargetValue();

        // 根据目标类型转换显示值
        if (TodoConstants.GOAL_TARGET_TYPE_DURATION.equals(setting.getGoalTargetType())) {
            // 如果是时长类型，需要将秒转换为分钟显示
            displayGoalValue = setting.getGoalTargetValue() / 60;
        } else if (TodoConstants.GOAL_TARGET_TYPE_TIMES.equals(setting.getGoalTargetType())) {
            unit = "次";
        }

        holder.tvTaskProgress.setVisibility(View.VISIBLE);
        holder.tvTaskProgress.setText(progress + "/" + displayGoalValue + unit);
        Log.d(TAG, "handleGoalMode: 更新任务进度显示: " + progress + "/" + displayGoalValue + unit);

        // 检查是否已完成目标
        boolean goalCompleted = false;
        if (TodoConstants.GOAL_TARGET_TYPE_DURATION.equals(setting.getGoalTargetType())) {
            // 对于时长类型，需要将目标值转换为分钟进行比较
            goalCompleted = progress >= (setting.getGoalTargetValue() / 60);
        } else {
            // 次数类型直接比较
            goalCompleted = progress >= setting.getGoalTargetValue();
        }

        if (goalCompleted) {
            // 目标已完成，标题添加删除线，按钮显示"已完成"
            holder.tvName.setPaintFlags(holder.tvName.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            holder.btnStart.setText("已完成");
            holder.btnStart.setEnabled(false);

            // 显示今日完成次数
            if (todayCompletedCount > 0) {
                holder.tvCompletionInfo.setVisibility(View.VISIBLE);
                holder.tvCompletionInfo.setText("今日已完成" + todayCompletedCount + "次");
            } else {
                holder.tvCompletionInfo.setVisibility(View.INVISIBLE);
            }
        } else {
            // 目标未完成，取消删除线，按钮显示"开始"
            holder.tvName.setPaintFlags(holder.tvName.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
            holder.btnStart.setText("开始");
            holder.btnStart.setEnabled(true);
            holder.tvCompletionInfo.setVisibility(View.INVISIBLE);
        }

        // 计算截止日期信息
        LocalDate deadline = LocalDate.parse(setting.getGoalDeadline());
        LocalDate today = LocalDate.now();
        long daysUntilDeadline = ChronoUnit.DAYS.between(today, deadline);

        if (daysUntilDeadline >= 0) {
            // 未超时
            holder.tvStartInfo.setVisibility(View.VISIBLE);
            holder.tvStartInfo.setText("截止" + daysUntilDeadline + "天");
        } else {
            // 已超时
            holder.tvStartInfo.setVisibility(View.VISIBLE);
            holder.tvStartInfo.setText("已超过设定时间");
        }

        // 隐藏普通番茄钟模式特有的UI元素
    }

    /**
     * 计算定目标任务的进度
     */
    private int calculateGoalProgress(TodoSettingDTO setting, List<TodoRecordSyncDTO> completedRecords) {
        if (TodoConstants.GOAL_TARGET_TYPE_DURATION.equals(setting.getGoalTargetType())) {
            // 按时长计算进度
            // 实际专注时间是以秒为单位存储的
            int totalSeconds = completedRecords.stream()
                    .mapToInt(record -> record.getActualFocusSeconds() != null ? record.getActualFocusSeconds() : 0)
                    .sum();
            int minutes = totalSeconds / 60; // 将秒转换为分钟
            Log.d(TAG, "calculateGoalProgress: 按时长计算进度，总秒数: " + totalSeconds + "，转换为分钟: " + minutes);
            return minutes;
        } else if (TodoConstants.GOAL_TARGET_TYPE_TIMES.equals(setting.getGoalTargetType())) {
            int count = completedRecords.size();
            Log.d(TAG, "calculateGoalProgress: 按次数计算进度，完成次数: " + count);
            return count;
        }
        return 0;
    }

    /**
     * 将专注记录保存到SharedPreferences
     *
     * @param context 上下文
     * @param record  要保存的记录
     */
    private void saveRecordToPreferences(Context context, TodoRecordSyncDTO record) {
        RecordUtil.saveRecordToPreferences(context, record);
    }
}
